<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Demo</title>
</head>
<body>
    <h1>WebSocket Demo</h1>
    <div id="messages"></div>
    <input type="text" id="messageInput" placeholder="输入消息">
    <button id="sendButton">发送</button>
    <script>
        // 建立WebSocket连接到本地3000端口
        const socket = new WebSocket('ws://localhost:3000');
        
        // 获取DOM元素
        const messagesDiv = document.getElementById('messages');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');

        // WebSocket消息处理
        socket.onmessage = (event) => {
            // 解析收到的JSON数据
            const data = JSON.parse(event.data);
            
            // 处理历史消息
            if (data.type === 'history') {
                data.data.forEach((msg) => {
                    const messageElement = document.createElement('p');
                    messageElement.textContent = msg.content;
                    messagesDiv.appendChild(messageElement);
                });
            } 
            // 处理新消息
            else if (data.type === 'message') {
                const messageElement = document.createElement('p');
                messageElement.textContent = data.data.content;
                messagesDiv.appendChild(messageElement);
            }
        };

        // 发送按钮点击事件
        sendButton.addEventListener('click', () => {
            const message = messageInput.value;
            if (message) {
                // 通过WebSocket发送消息
                socket.send(message);
                messageInput.value = '';
            }
        });
    </script>
</body>
</html>